package main

import (
	"context"
	"grpc-test/rpc"
	"grpc-test/server/etcd"
	"grpc-test/server/model"
	"log"
	"net"
	"os"

	"google.golang.org/grpc"
)

func main() {

	if len(os.Args) != 2 {
		panic("必须携带一个端口")
	}

	addr := "localhost:" + os.Args[1]

	// 将该服务注册到etcd上
	err := etcd.Register(addr)
	if err != nil {
		panic(err)
	}

	defer etcd.UnRegister(addr)

	lis, err := net.Listen("tcp", addr)
	if err != nil {
		panic(err)
	}

	// 创建grpc的server
	server := grpc.NewServer(grpc.UnaryInterceptor(UnaryInterceptor()))
	
	rpc.RegisterCalculationServer(server, model.CalculationServer{})

	// 开启grpc服务
	err = server.Serve(lis)
	if err != nil {
		panic(err)
	}
}

// 自定义拦截器
func UnaryInterceptor() grpc.UnaryServerInterceptor {
	return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
		log.Printf("call %s\n", info.FullMethod)
		resp, err = handler(ctx, req)
		return resp, err
	}
}